﻿-----------------------
-- Name: Show IRQ Scanline for Mesen
-- Author: FlameCyclone
-- Date: 2023.8.5
-----------------------
-- Draws a line for IRQ
-----------------------

local consoleType = emu.getState()["consoleType"]
if consoleType ~= "Nes" then
  emu.displayMessage("Script", "This script only works on the NES.")
  return
end

function on_irq()
    line_color   = 0x00ffff00
    bkg_color    = 0xf0000000
    text_color   = 0x00ffff00
    irq_scanline     = emu.getState()['ppu.scanline']
    
    nmi_addr = emu.readWord(0xfffa, emu.memType.nesDebug , false)
    reset_addr = emu.readWord(0xfffc, emu.memType.nesDebug , false)
    irq_addr = emu.readWord(0xfffe, emu.memType.nesDebug , false)
    emu.drawLine(0, irq_scanline, 256, irq_scanline, line_color, 1)
    
    emu.drawString(1, 10 * 1, string.format("nmi: $%04X", nmi_addr), text_color, bkg_color)
    emu.drawString(1, 10 * 2, string.format("reset: $%04X", reset_addr), text_color, bkg_color)
    emu.drawString(1, 10 * 3, string.format("irq: $%04X", irq_addr), text_color, bkg_color)
    emu.drawString(0, irq_scanline + 2, irq_scanline, text_color, bkg_color)
end

last_cycle = emu.getState()['cpu.cycleCount']
function on_addr_write(addr, val)
    line_color   = 0x00ffff00
    bkg_color    = 0xf0000000
    text_color   = 0x00ffff00
    if 0x80 == val then
    
    cur_cycle = emu.getState()['cpu.cycleCount']
    cycle_intval = cur_cycle - last_cycle
    last_cycle = cur_cycle
    nmi_addr = emu.readWord(0xfffa, emu.memType.nesDebug , false)
    reset_addr = emu.readWord(0xfffc, emu.memType.nesDebug , false)
    irq_addr = emu.readWord(0xfffe, emu.memType.nesDebug , false)
    
    if cycle_intval > 30000 then
    emu.drawString(1, 8 * 1, string.format("cycle: %d cur_cycle: %d last_cycle: %d", cycle_intval, cur_cycle, last_cycle), text_color, bkg_color)
    end
    
    end
end

function on_nmi()
    line_color   = 0x00ffff00
    bkg_color    = 0xf0000000
    text_color   = 0x00ffff00
    
    cur_cycle = emu.getState()['cpu.cycleCount']
    cycle_intval = cur_cycle - last_cycle
    last_cycle = cur_cycle
    nmi_addr = emu.readWord(0xfffa, emu.memType.nesDebug , false)
    reset_addr = emu.readWord(0xfffc, emu.memType.nesDebug , false)
    irq_addr = emu.readWord(0xfffe, emu.memType.nesDebug , false)
    
    if cycle_intval > 30000 then
        emu.drawString(1, 8 * 1, string.format("cycle: %d cur_cycle: %d last_cycle: %d", cycle_intval, cur_cycle, last_cycle), text_color, bkg_color)
        --emu.breakExecution()
    end
    
end

emu.addEventCallback(on_nmi, emu.eventType.nmi)
--emu.addMemoryCallback(on_addr_write, emu.callbackType.write, 0x5204)
--emu.addEventCallback(on_irq, emu.eventType.reset)
--emu.addEventCallback(on_irq, emu.eventType.nmi)
--emu.addEventCallback(on_irq, emu.eventType.irq)
emu.displayMessage("Script", "Irq Scanline")
